import cv2
import numpy as np
import matplotlib.pyplot as plt

class sobel:
    def __init__(self, img_path):
      self.img = cv2.imread(img_path)
      self.temp1=np.zeros(self.img.shape,dtype=np.uint8)
      self.temp2=np.zeros(self.img.shape,dtype=np.uint8)
      self.out=np.zeros(self.img.shape,dtype=np.uint8)
      self.K1=np.array([[-1,0,1],
                        [-2,0,2],
                        [-1,0,1]])
      self.K2=np.array([[1,2,1],
                        [0,0,0],
                        [-1,-2,-1]])
      self.R=3//2      
      
        
    def padding(self,K_size):
        [H,W,C]=self.img.shape
        R=K_size//2
        p=np.zeros((H+2*R,W+2*R,C),dtype=np.uint8)
        p[R:R+H,R:R+W,:]=self.img.copy().astype(np.uint8)
        p[0:R,0:R,:]=self.img[0,0,:]
        p[0:R,R+W:2*R+W,:]=self.img[0,W-1,:]
        p[H+R:H+2*R,0:R,:]=self.img[H-1,0,:]
        p[H+R:H+2*R,R+W:2*R+W,:]=self.img[H-1,W-1,:]
        for i in range(R):
            p[i,R:R+W,:]=self.img[0,:,:]
            p[R+H+i,R:R+W,:]=self.img[-1,:,:]
            p[R:R+H,i,:]=self.img[:,0,:]
            p[R:R+H,R+W+i,:]=self.img[:,-1,:] 
        return p
    
    
    def operation(self,p):
        [H,W,C]=self.img.shape
        for x in range(H):
            print(x)
            for y in range(W):
                for c in range(C):
                    self.temp1[x,y,c]=np.sum(self.K1*p[x:x+3,y:y+3,c])
                    self.temp2[x,y,c]=np.sum(self.K2*p[x:x+3,y:y+3,c])
        self.out=np.sqrt(self.temp1**2+self.temp2**2)
        self.out=((self.out-np.amin(self.out))/(np.amax(self.out)-np.amin(self.out))*255).astype(np.uint8)
        for q in range(H):
            for w in range(W):
                for e in range(C):
                    if self.out[q,w,e]<245:
                        self.out[q,w,e]=0
                    

    
if __name__ == "__main__":
    s=sobel('YOIMIYA.jpg')
    p=s.padding(3).copy().astype(np.uint8)
    s.operation(p)
    print(s.out)
    compare = np.hstack([s.img , s.out ])
    cv2.imshow('compare',compare)
    cv2.waitKey(0)                  
                    
                
                
        
        
        
        
    